<?php
namespace db;

class MysqlDatabase implements Database {
	/**
	 *
	 * @var \mysqli
	 */
	protected $conn;

	function __construct(\mysqli $cfgOrConnection) {
		if ($cfgOrConnection instanceof \mysqli)
			$this->conn = $cfgOrConnection;
		else if ($cfgOrConnection instanceof DatabaseConfig)
			$this->conn = new \mysqli($cfgOrConnection->getHost(), $cfgOrConnection->getUsername(), $cfgOrConnection->getPassword(), $cfgOrConnection->getName());
		else
			throw new \InvalidArgumentException("argument must be instance of mysqli or db\\DatabaseConfig");
	}

	function run($query) {
		if (!is_string($query))
			throw new \InvalidArgumentException("query has to be a string");
		
		$response = $this->conn->query($query);
		if (!$response)
			throw new SqlException($this->conn->error);
		if ($response === true)
			return null;
		return new MysqlQueryResult($response, $this->conn);
	}
	
	function escapeString($string) {
		return $this->conn->escape_string($string);
	}

	function beginTransaction() {
		return $this->conn->autocommit(false);
	}

	function rollback() {
		$result = $this->conn->rollback();
		$this->conn->autocommit(true);
		return $result;
	}

	function commit() {
		$result = $this->conn->commit();
		$this->conn->autocommit(true);
		return $result;
	}

	function close() {
		$this->conn->close();
	}
}